 
import { PositionHelper } from "utils/position/PositionHelper";
import { ActionBase, ActionBaseOfCreep } from "../ActionBase";
import { EActionCode } from "framework/FSM/Action/ActionCode";

/**
 * 升级Action
 */
export class ActionMoveTo  extends ActionBaseOfCreep<IActionCMD<"moveto">>
{
    protected _execute(action: IActionCMD<"moveto">): ActionCode 
    {
        const creep = action.arg.entity;
        creep.log('info','moveto',action.arg.goal.pos,JSON.stringify(action.arg.opt))
        const opt = _.cloneDeep(action.arg.opt);
        if(action.arg.opt.portal == 1 && this.moveCenterPortal(action.arg.entity as Creep,action.arg.goal.pos.roomName))
        {
            return EActionCode.RUNNING;
        }
        
        
         
        if(action.arg.activerange)
        {
            if(action.arg.entity.pos.distance(action.arg.goal.pos)>action.arg.activerange)
            {
                creep.log('info','moveto1' ,JSON.stringify(action.arg.opt))
                action.arg.entity.mymoveTo(action.arg.goal,opt);
            }
            else 
            {
                action.arg.entity.memory._move=undefined;
                action.arg.entity.memory._route = undefined;
                return   EActionCode.OK;
            }
            
            
        }
        else 
        {
            if(action.arg.entity.pos.distance(action.arg.goal.pos)>action.arg.goal.range)
            {
                creep.log('info','moveto2' ,JSON.stringify(action.arg.opt))
                action.arg.entity.mymoveTo(action.arg.goal,opt);
            }
            else 
            {
                action.arg.entity.memory._move=undefined;
                return   EActionCode.OK;
            }
        }
        return   EActionCode.RUNNING;
    }

    private moveCenterPortal(creep:Creep,targetRoom:string) 
    {
        const centerroom = PositionHelper.getCenterRoom(creep.room.name);
        if(Game.map.getRoomLinearDistance(centerroom,targetRoom) <=5)
        {
            // 这个中央房已经接近目标房间了
            return false;
        }
        const room = Game.rooms[centerroom];
        const centerP = PositionHelper.Create({x:25,y:25,roomName:centerroom});
        if(room )
        {
            // 有视野
            const portal = room.getStructures(STRUCTURE_PORTAL)[0];
            creep.mymoveTo({pos:portal.pos,range:0},{IsRealtime:true,IsPassPortal:true});
        }
        else 
        {
            // 无视野
            
            if(creep.pos.distance(centerP)>22)
            {
                creep.mymoveTo({pos:centerP,range:10},{IsRealtime:true,IsPassPortal:true});
            }
            else 
            {
                 
            }
        }
        return true;
    }
}